package com.example.bankseckill.utils;

import com.example.bankseckill.pojo.User;
import com.example.bankseckill.pojo.vo.RespBean;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liyangjing
 * @Date: 2022/02/12/20:35
 * @Description:
 *
 * 这是一个获取多个user token 的工具类
 * 来方便多用户并发量测试的工具类
 * 为了方便 我要将 登录验证码去掉 （测试完成后添加）
 *
 * 消除了logincotroller 的@RequestBody @Valid (方便)
 *
 *
 */
public class GetUserTokenUtil {
    /**
     * 创建数据库连接
     * @return
     * @throws Exception
     */
    private static Connection getConn() throws Exception {
        String url = "jdbc:mysql://127.0.0.1:3306/bank?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
        String username = "root";
        String password = "qqq111";
        String driver = "com.mysql.cj.jdbc.Driver";
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

    public static void createUser(int count) throws Exception {
        /**
         * 生成user对象
         */
        List<User> users = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setIdentitycard("130000"+i);
            user.setName(i+"");
            user.setAge(19);
            user.setUsername(i+"");
            user.setPhone("13822"+i);
            user.setPassword("b7797cce01b4b131b433b6acf4add449");
            user.setAdmin(0);
            user.setIsinwork(1);
            user.setRiskLevel(0);
            user.setEnable(1);
            user.setIshonest(0);
            users.add(user);
        }
//        //插入数据库 生成count个user用户
//        Connection conn = getConn();
//        String sql = "insert into t_user(identitycard, name, age, username, password, admin,phone,risk_level,isinwork,ishonest,enable)values(?,?,?,?,?,?,?,?,?,?,?)";
//        PreparedStatement pstmt = conn.prepareStatement(sql);
//        for (int i = 0; i < users.size()-1; i++) {
//            User user = users.get(i);
//            pstmt.setString(1, user.getIdentitycard());
//            pstmt.setString(2, user.getName());
//            pstmt.setInt(3,user.getAge());
//            pstmt.setString(4, user.getUsername());
//            pstmt.setString(5, user.getPassword());
//            pstmt.setInt(6, user.getAdmin());
//            pstmt.setString(7, user.getPhone());
//            pstmt.setInt(8,user.getRiskLevel());
//            pstmt.setInt(9,user.getIsinwork());
//            pstmt.setInt(10,user.getIshonest());
//            pstmt.setInt(11,user.getEnable());
//            pstmt.addBatch();
//        }
//        pstmt.executeBatch();
//        pstmt.close();
//        conn.close();
//        System.out.println("insert to db");

        //通过访问接口login 得到token 再将token存入 txt文件
        String urlString = "http://localhost:8081/bank/login";
        File file = new File("E:\\2022waiibao\\gitee\\bankproject\\config.txt");
        if (file.exists()) {
            file.delete();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        file.createNewFile();
        raf.seek(0);
        //循环user 访问登录地址 得到token 存入txt文件
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            System.out.println(user);
            URL url = new URL(urlString);
            HttpURLConnection co = (HttpURLConnection) url.openConnection();
            co.setRequestMethod("POST");
            co.setDoOutput(true);
            OutputStream out = co.getOutputStream();
            String params = "phone="+user.getPhone()+"&password="+"d3b1294a61a07da9b49b6e22b2cbd7f9";
            out.write(params.getBytes());
            out.flush();
            InputStream inputStream = co.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte buff[] = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) >= 0) {
                bout.write(buff, 0, len);
            }
            inputStream.close();
            //config.txt
            bout.close();
            String response = new String(bout.toByteArray());
            ObjectMapper mapper = new ObjectMapper();
            RespBean respBean = mapper.readValue(response, RespBean.class);
            String token = (String) respBean.getObj();
            System.out.println(respBean);
            String row = "token" + "," + token;
            raf.seek(raf.length());
            raf.write(row.getBytes());
            raf.write("\r\n".getBytes());
            System.out.println("write to file : " + user.getId());
        }
        raf.close();
        System.out.println("over");
    }
    public static void main(String[] args) throws Exception {
        createUser(10000);
//        String urlString = "http://localhost:8081/bank/login";
//        URL url = new URL(urlString);
//        HttpURLConnection co = (HttpURLConnection) url.openConnection();
//        co.setRequestMethod("POST");
//        co.setDoOutput(true);
//        OutputStream out = co.getOutputStream();
//        String params = "phone=18084998473&password=d3b1294a61a07da9b49b6e22b2cbd7f9";
//        out.write(params.getBytes());
//        out.flush();
//        InputStream inputStream = co.getInputStream();
//        ByteArrayOutputStream bout = new ByteArrayOutputStream();
//        byte buff[] = new byte[1024];
//        int len = 0;
//        while ((len = inputStream.read(buff)) >= 0) {
//            bout.write(buff, 0, len);
//        }
//        inputStream.close();
//        //config.txt
//        bout.close();
//        String response = new String(bout.toByteArray());
//        ObjectMapper mapper = new ObjectMapper();
//        RespBean respBean = mapper.readValue(response, RespBean.class);
//        String token = (String) respBean.getObj();
//        System.out.println(respBean);
//        String row = "token" + "," + token;
//        System.out.println(token);
    }
}
